package com.andy.nature.ui.activity

import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import com.andy.common.base.BaseVMActivity
import com.andy.common.extend.formatMilliSecondTime
import com.andy.common.extend.formatTime
import com.andy.common.extend.setOnIMClickListener
import com.andy.common.model.Label
import com.andy.common.model.Work
import com.andy.dialog.showDialog
import com.andy.logcat.LogUtils
import com.andy.nature.R
import com.andy.nature.databinding.ActivityRecruitBinding
import com.andy.nature.databinding.DialogCustomLayoutBinding
import com.andy.nature.databinding.DialogMiddleListBinding
import com.andy.nature.databinding.DialogMiddleListTitleBinding
import com.andy.nature.ui.adapter.*
import com.andy.nature.utils.ActivityUtils
import com.andy.nature.utils.ShareUtils
import com.andy.nature.vm.RecruitViewModel
import com.andy.permission.constants.Constants
import com.andy.permission.utils.PermissionUtils
import com.andy.toast.extend.showErrorToast
import com.andy.toast.extend.showNormalToast
import com.andy.toast.extend.showSuccessToast
import com.sch.share.WXShareMultiImageHelper

/**
 * Author:Andy
 * Date:2023/4/27 17:51
 * Description:RecruitActivity
 */
class RecruitActivity : BaseVMActivity<ActivityRecruitBinding, RecruitViewModel>() {
    private val mCommonLabelAdapter: CommonLabelAdapter by lazy {
        CommonLabelAdapter()
    }
    private val mShareCircleAdapter: RecruitShareAdapter by lazy {
        RecruitShareAdapter()
    }
    private val mShareFriendsAdapter: RecruitShareAdapter by lazy {
        RecruitShareAdapter()
    }
    private val mWorkAdapter: RecruitAdapter by lazy {
        RecruitAdapter()
    }
    private var selectLabel: Label? = null

    private var isKeyShare = false

    private var workList: MutableList<Work> = mutableListOf()
    private var groupList: List<List<Work>> = mutableListOf()
    private var isVisible = false
    private var delayTime = 30 * 30000L

    override fun viewModelClass(): Class<RecruitViewModel> {
        return RecruitViewModel::class.java
    }

    override fun getViewBinding(): ActivityRecruitBinding {
        return ActivityRecruitBinding.inflate(layoutInflater)
    }

    override fun initObserve() {
        mViewModel.commonLabelData.observe(this) {
            mCommonLabelAdapter.setData(it)
            val list = mCommonLabelAdapter.getCommonLabelIds()
            mViewModel.getRecruitList(ids = list, is_except = 1)
        }
        mViewModel.workData.observe(this) {
            "获取了${it.size}个岗位".showNormalToast()
            LogUtils.e("Ancoding", "获取了${it.size}个岗位")
            if (it.isNullOrEmpty()) {
                mBinding?.tvWechatCircle?.isVisible = false
                mBinding?.tvWechatFriends?.isVisible = false
            } else {
                mBinding?.tvWechatCircle?.isVisible = true
                mBinding?.tvWechatFriends?.isVisible = true
            }
            mWorkAdapter.setData(selectLabel, it, mViewModel.totalLabelList)
            workList = mWorkAdapter.getWorkList()
            groupList = averageAssignFixLength(workList, 9)
            val groupCount = groupList.size
            "岗位一共分${groupCount}组".showNormalToast()
            LogUtils.e("Ancoding", "岗位一共分${groupCount}组")
            mShareCircleAdapter.setData(groupCount, true)
            mShareFriendsAdapter.setData(groupCount, false)
            //去生成二维码用于分享
            val list = ArrayList<String>()
            val selectList = mWorkAdapter.getWorkList()
            selectList.forEach { work ->
                if (work.name != "汇总") {
                    list.add(work.id ?: "")
                }
            }
            mViewModel.createQrcode(list)
            if (isKeyShare) {
                goShareByPosition(groupCount, 0)
            }
        }
        mViewModel.createLiveData.observe(this) {
            LogUtils.e("Ancoding", "创建二维码${it}")
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun initData() {
        mBinding?.apply {
            rvLabelList.adapter = mCommonLabelAdapter
            rvShareWechatCircle.adapter = mShareCircleAdapter
            rvShareWechatFriends.adapter = mShareFriendsAdapter
            rvWorkList.adapter = mWorkAdapter
        }
        PermissionUtils.checkAndRequestPermissions(this@RecruitActivity, Constants.READ_MEDIA) { isGranted, isNotAskAgain ->
            if (!isGranted && isNotAskAgain) {
                PermissionUtils.jumpAndStartPermissions(this@RecruitActivity, Constants.READ_MEDIA)
            }
        }
    }

    override fun initAction() {
        mBinding?.apply {
            tvFilter.setOnIMClickListener {
                isKeyShare = false
                showLabelDialog()
            }
            tvSearch.setOnIMClickListener {
                val keyword = edtInput.text.toString().trim()
                if (keyword.isEmpty()) {
                    "请输入关键词".showErrorToast()
                    return@setOnIMClickListener
                }
                mViewModel.getRecruitList(keyword)

            }
            tvShare.setOnIMClickListener {
                isKeyShare = true
                checkPermission {
                    if (it) {
                        "权限开启成功".showSuccessToast()
                        val allCommonLabelList = mCommonLabelAdapter.getCommonLabelList()
                        getRecruitDataByLabel(allCommonLabelList, 0)
                    } else {
                        "权限开启失败".showSuccessToast()
                    }
                }
            }
        }
        mCommonLabelAdapter.setActionListener(object : CommonLabelAdapter.ActionListener {
            override fun click(data: Label, labelList: List<Label>) {
                isKeyShare = false
                selectLabel = data
                if (data.id.isNullOrEmpty()) {
                    val list = mCommonLabelAdapter.getCommonLabelIds()
                    mViewModel.getRecruitList(ids = list, is_except = 1)
                } else {
                    val list = ArrayList<String>()
                    list.add(data.id ?: "")
                    mViewModel.getRecruitList(ids = list, is_except = 0)
                }
            }
        })
        mShareCircleAdapter.setActionListener(object : RecruitShareAdapter.ActionListener {
            override fun click(position: Int, isCircle: Boolean) {
                isKeyShare = false
                checkPermission {
                    if (it) {
                        "权限开启成功".showSuccessToast()
                        showPosterDialog(position, true)
                    } else {
                        "权限开启失败".showSuccessToast()
                    }
                }
            }
        })
        mShareFriendsAdapter.setActionListener(object : RecruitShareAdapter.ActionListener {
            override fun click(position: Int, isCircle: Boolean) {
                isKeyShare = false
                checkPermission {
                    if (it) {
                        "权限开启成功".showSuccessToast()
                        showPosterDialog(position, false)
                    } else {
                        "权限开启失败".showSuccessToast()
                    }
                }
            }
        })
    }

    private fun checkPermission(cb: (isSuccess: Boolean) -> Unit) {
        if (!WXShareMultiImageHelper.isServiceEnabled(this)) {
            showDialog {
                addLayout(R.layout.dialog_custom_layout)
                bind<DialogCustomLayoutBinding> {
                    it.dialogMessage.text = "请点击确定开启快聘123服务权限"
                    it.dialogCancel.isVisible = true
                    it.dialogButtonLine.isVisible = true
                    it.dialogConfirm.setOnIMClickListener {
                        WXShareMultiImageHelper.openService(this@RecruitActivity) { isEnable ->
                            cb.invoke(isEnable)
                        }
                        dismiss()
                    }
                    it.dialogCancel.setOnIMClickListener {
                        dismiss()
                    }
                }
            }
        } else {
            cb.invoke(true)
        }
    }

    //递归间隔60秒获取一个标签对应的工作岗位
    private fun getRecruitDataByLabel(all: MutableList<Label>, position: Int) {
        if (isKeyShare) {
            var index = position
            if (all.size > index) {
                val label = all[index]
                selectLabel = label
                "开始获取${label.name}的招聘岗位".showNormalToast()
                LogUtils.e("Ancoding", "开始获取${label.name}的招聘岗位")
                if (!isVisible) {
                    ActivityUtils.backForeground(this@RecruitActivity)
                }
                if (label.id.isNullOrEmpty()) {
                    val list = mCommonLabelAdapter.getCommonLabelIds()
                    mViewModel.getRecruitList(ids = list, is_except = 1) {
                        delayTime = it * 30000L
                        index += 1
                        delayRequestNext(all, index)
                    }
                } else {
                    val list = ArrayList<String>()
                    list.add(label.id ?: "")
                    mViewModel.getRecruitList(ids = list, is_except = 0) {
                        delayTime = it * 30000L
                        index += 1
                        delayRequestNext(all, index)
                    }
                }
            }
        }
    }

    private fun delayRequestNext(all: MutableList<Label>, position: Int) {
        "${delayTime / 1000}秒后获取第${position}个标签的岗位".showNormalToast()
        LogUtils.e("Ancoding", "${delayTime / 1000}秒后获取第${position}个标签的岗位")
        mBinding?.tvShare?.postDelayed({
            if (isKeyShare) {
                getRecruitDataByLabel(all, position)
            }
        }, delayTime)
    }

    //递归间隔20秒分享一组工作岗位
    private fun goShareByPosition(groupCount: Int, position: Int) {
        if (isKeyShare) {
            var p = position
            if (groupCount > p) {
                "开始裁剪${position + 1}组岗位信息".showNormalToast()
                LogUtils.e("Ancoding", "开始裁剪${position + 1}组岗位信息")
                showPosterDialog(position, true)
                p += 1
                mBinding?.tvShare?.postDelayed({
                    if (isKeyShare) {
                        goShareByPosition(groupCount, p)
                    }
                }, 20000)
            }
        }
    }

    private fun showLabelDialog() {
        showDialog {
            addLayout(R.layout.dialog_middle_list_title)
            bind<DialogMiddleListTitleBinding> {
                val adapter = DialogLabelAdapter()
                it.dialogRecycler.layoutManager = GridLayoutManager(this.context, 3)
                it.dialogRecycler.adapter = adapter
                adapter.setData(mViewModel.totalLabelList, mCommonLabelAdapter.getCommonLabelList())
                it.tvReset.setOnIMClickListener {
                    adapter.resetData()
                }
                it.tvSet.setOnIMClickListener {
                    val selectList = adapter.getSelectList()
                    mViewModel.setCommonLabelList(selectList)
                    dismiss()
                }
            }
        }
    }

    private fun showPosterDialog(position: Int, isCircle: Boolean) {
        if (groupList.isNotEmpty()) {
            if (!isVisible) {
                ActivityUtils.backForeground(this@RecruitActivity)
                mBinding?.tvShare?.postDelayed({
                    goCropPoster(position, isCircle)
                }, 2500)
            } else {
                goCropPoster(position, isCircle)
            }
        } else {
            "暂无招聘信息".showErrorToast()
        }
    }

    private fun goCropPoster(position: Int, isCircle: Boolean) {
        val labelList = mWorkAdapter.getLabelList()
        showDialog {
            addLayout(R.layout.dialog_middle_list)
            bind<DialogMiddleListBinding> {
                val adapter = PosterAdapter()
                it.dialogRecycler.layoutManager = GridLayoutManager(this.context, 1)
                it.dialogRecycler.adapter = adapter
                adapter.setData(groupList[position], labelList)
                val title = getDateTitle()
                it.dialogRecycler.postDelayed({
                    val sharePosterList = adapter.getSharePostList()
                    if (isCircle) {
                        "开始分享${position + 1}组到朋友圈".showNormalToast()
                        LogUtils.e("Ancoding", "开始分享${position + 1}组到朋友圈")
                        ShareUtils.shareToWechatCircle(this@RecruitActivity, title, sharePosterList)
                    } else {
                        "开始分享${position + 1}组到好友".showNormalToast()
                        LogUtils.e("Ancoding", "开始分享${position + 1}组到好友")
                        ShareUtils.shareToWechatFriends(this@RecruitActivity, sharePosterList)
                    }
                    dismiss()
                }, 2200)
            }
        }
    }

    private fun <T> averageAssignFixLength(source: List<T>?, splitItemNum: Int): List<List<T>> {
        val result = ArrayList<List<T>>()
        if (source != null && source.run { isNotEmpty() } && splitItemNum > 0) {
            if (source.size <= splitItemNum) {
                // 源List元素数量小于等于目标分组数量
                result.add(source)
            } else {
                // 计算拆分后list数量
                val splitNum = if (source.size % splitItemNum == 0) source.size / splitItemNum else source.size / splitItemNum + 1
                var value: List<T>? = null
                for (i in 0 until splitNum) {
                    value = if (i < splitNum - 1) {
                        source.subList(i * splitItemNum, (i + 1) * splitItemNum)
                    } else {
                        // 最后一组
                        source.subList(i * splitItemNum, source.size)
                    }
                    result.add(value)
                }
            }
        }
        return result
    }

    private fun getDateTitle(): String {
        val current = System.currentTimeMillis()
        val tmp = current.formatTime()
        val tamp = ShareUtils.dateToStamp("$tmp 15:00:00")
        val date = if (current > tamp) {
            (current + 24 * 60 * 60 * 1000).formatMilliSecondTime()
        } else {
            current.formatMilliSecondTime()
        }
        return "$date 123快聘${selectLabel?.name ?: "最新招聘信息"}企业推荐"
    }

    override fun onResume() {
        super.onResume()
        isVisible = true
    }

    override fun onStop() {
        super.onStop()
        isVisible = false
    }
}